const qiniu = require('qiniu');
const uuid = require('uuid');
const config = require('@/config/qiniu'); // 你的七牛云配置文件
const fs = require('fs');

const mac = new qiniu.auth.digest.Mac(config.accessKey, config.secretKey);
const qnConfig = new qiniu.conf.Config();
qnConfig.zone = qiniu.zone[config.zone];
const formUploader = new qiniu.form_up.FormUploader(qnConfig);

function generateToken(key) {
  const putPolicy = new qiniu.rs.PutPolicy({
    scope: `${config.bucket}:${key}`,
    expires: 7200,
    returnBody: `{"key":"$(key)","url":"http://${config.origin}/$(key)"}`
  });
  return putPolicy.uploadToken(mac);
}

/**
 * 上传文件到七牛云
 * @param {Object} file koa-body/files对象 或 { filepath, originalFilename }
 * @returns {Promise<string>} 七牛云文件URL
 */
function uploadToQiniu(file) {
  return new Promise((resolve, reject) => {
    // 兼容 koa-body 和 busboy 的 file 对象
    const filePath = file.filepath || file.path;
    const originalName = file.originalFilename || file.name || 'file';
    const ext = originalName.split('.').pop();
    const key = `albums/${uuid.v4()}.${ext}`;
    const token = generateToken(key);
    const stream = fs.createReadStream(filePath);

    formUploader.putStream(
      token,
      key,
      stream,
      new qiniu.form_up.PutExtra(),
      (err, body) => {
        if (err) {
          stream.destroy();
          return reject(err);
        }
        resolve(body.url);
      }
    );
  });
}

async function deleteQiniuFile(key) {
  const bucketManager = new qiniu.rs.BucketManager(mac, qnConfig);
  const result = await bucketManager.delete(config.bucket, key, { force: false });
  return result;
}

module.exports = {
  uploadToQiniu,
  deleteQiniuFile
};
